package com.yuec.epidemic;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.yuec.epidemic.mapper")
public class MybatisConfig {

    private static Logger logger = Logger.getLogger(MybatisConfig.class);

    //配置数据源
    @Bean(name = "dataSource", destroyMethod = "close")
    public BasicDataSource basicDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/epidemic?serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("5499");

        dataSource.setInitialSize(20);
        dataSource.setMaxActive(50);
        dataSource.setMaxIdle(5);
        dataSource.setMaxWait(5000);
        dataSource.setDefaultAutoCommit(false);

        return dataSource;
    }


    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {

        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        SqlSessionFactory factory = null;

        factoryBean.setTypeAliasesPackage("com.yuec.epidemic.dto");

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(configuration);

        try {
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:com/yuec/epidemic/mapper/*Mapper.xml");
            factoryBean.setMapperLocations(resources);
            factory = factoryBean.getObject();
        } catch (Exception e) {
            logger.error("解析映射xml文件异常" + e.getMessage());
        }


        return factory;
    }

}
